import { defineStore } from 'pinia'
import { useAppStore } from './app'
import { _API_Login, _API_GetInfo } from '@/api'
import type { UserInfoType } from '@/api/interface'
import util from '@/utils/util'

export const useUserStore = defineStore('user', {
  state: () => {
    return {
      token: '',
      loginState: false,
      info: {
        id: 0,
        nickname: '',
        avatar: '',
        mobile: '',
        gender: 0,
        tag: {
          id: 0,
          name: ''
        },
        follow_num: 0,
        fans_num: 0,
        like_num: 0
      } as UserInfoType
    }
  },
  actions: {
    login() {
      const _this = this
      uni.login({
        success({ code }) {
          _API_Login(code).then((res) => {
            _this.setToken(res.access_token)
            _this.getUserInfo()
          })
        }
      })
    },
    setToken(token: string) {
      this.token = token
      util.setLocal('token', token)
    },
    getUserInfo(callback?: () => void) {
      _API_GetInfo()
        .then((res) => {
          this.info = res
          if (res.mobile) {
            this.loginState = true
          }
          if (callback) {
            callback()
          } else {
            useAppStore().vm!.$isResolve()
          }
        })
        .catch(() => {
          if (callback) {
            callback()
          }
        })
    }
  }
})
